package com.cupk.controller;

import com.cupk.pojo.Result;
import com.cupk.pojo.Topic;
import com.cupk.pojo.Stage;
import com.cupk.service.StageService;
import com.cupk.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/topic")
public class TopicController {
    @Autowired
    private TopicService topicService;
    @Autowired
    private StageService stageService;

    @PostMapping("/add")
    public Result addTopic(@RequestBody Topic topic) {
        Integer stageId = topic.getStageId();
        Stage stage = stageService.getStageById(stageId);
        if (stage == null) {
            return Result.error("比赛阶段不存在，无法添加题目！");
        }
        List<Topic> ls = topicService.getTopicByStageId(stageId);
        if (stage.getRule() != Stage.AUTO_APPROVE_FORM && stage.getRule() != Stage.MANUAL_APPROVE_FORM && ls.size() >= 1) {
            return Result.error("当前比赛策略下不允许创建多个题目！");
        }
        Integer question = topicService.findMaxQuestion(stageId) + 1;
        topic.setQuestionId(question);
        topicService.addTopic(topic);
        return Result.success();
    }

    @PutMapping("/update")
    public Result updateTopic(@RequestBody Topic topic) {
        Integer topicId = topic.getId();
        Topic res = topicService.getTopicById(topicId);
        if (res == null) {
            return Result.error("题目ID请求非法！");
        }
        topicService.updateTopic(topic);
        return Result.success();
    }

    @GetMapping("/list")
    public Result getTopicList(@RequestParam Integer id) {
        List<Topic> ls = topicService.getTopicByStageId(id);
        for (Topic l : ls) {
            l = topicService.transferChoice(l);
        }
        return Result.success(ls);
    }

    @GetMapping("/detail")
    public Result getTopicDetail(@RequestParam Integer id) {
        Topic topic = topicService.getTopicById(id);
        if (topic == null) {
            return Result.error("题目ID请求非法！");
        }
        topic = topicService.transferChoice(topic);
        return Result.success(topic);
    }

    @DeleteMapping("/del")
    public Result delTopic(@RequestParam Integer id) {
        Topic topic = topicService.getTopicById(id);
        if (topic == null) {
            return Result.error("题目ID请求非法！");
        }
        topicService.deleteTopic(id);
        return Result.success();
    }

    @GetMapping("/getDetailTopic")
    public Result<List<Topic>> getDetailStage(@RequestParam Integer stageId) {
        List<Topic> ls = topicService.getTopicByStageId(stageId);
        if (ls == null) {
            return Result.error("当前阶段无题目！请尝试联系管理员处理！");
        }
        for (Topic l : ls) {
            l = topicService.transferChoice(l);
        }
        return Result.success(ls);
    }
}

